ConfirmRepo = new Object();

Ext.define('PrimaryDealer', {
	extend : 'Ext.data.Model',
	fields : [ {
		name : 'code',
		type : 'string'
	}, {
		name : 'name',
		type : 'string'
	} ]
});

var primaryDealerStore = new Ext.data.Store({
	model : 'PrimaryDealer'
});

ConfirmRepo.getSearchBar = function() {

	return Ext.create('Ext.form.FieldContainer', {
		items : [ {
			xtype : 'triggerfield',
			id : 'confirmRepoTrigField',
			triggerCls : 'x-form-search-trigger',
			anchor : '28%',
			style : 'float:right;',
			emptyText : 'Search Repos',
			listeners : {
				specialkey : function(field, e) {
					if (e.getKey() == e.ENTER) {
						Ext.Msg.alert('HI', 'Press Enter');
					}
				}
			},
			onTriggerClick : function() {
				var searchResult = Ext.create('Ext.data.Store', {
					fields : [ 'id', 'dealCode', 'issuer', 'status' ]
				});
				var TrigField = Ext.ComponentQuery.query('#confirmRepoTrigField')[0];

				Ext.Ajax.request({
					url : 'getRepos.action',
					params : {
						queryOne : TrigField.getValue(),
					},
					success : function(response) {
						var obj = Ext.decode(response.responseText);
						var arrayLength = obj.deals.length;
						for (var i = 0; i < arrayLength; i++) {
							searchResult.add({
								id : obj.deals[i].id,
								dealCode : obj.deals[i].dealCode,
								issuer : obj.deals[i].issuer.code,
								name : obj.deals[i].name,
								status : obj.deals[i].status,
							});
						}
					}
				});

				var resultWindow = Ext.create('Ext.grid.Panel', {
					defaults : {
						anchor : '100%'
					},
					store : searchResult,
					columns : [ {
						text : 'Deal Code',
						dataIndex : 'dealCode',
						flex : 1
					}, {
						text : 'Issuer',
						dataIndex : 'issuer',
						flex : 1
					}, {
						text : 'Status',
						dataIndex : 'status',
						flex : 1
					} ],

					listeners : {
						itemclick : function(view, rec, item, index, eventObj) {
							var findId = rec.get('id');
							var formPanl = Ext.ComponentQuery.query('#confirmRepoFormPanel')[0];
							formPanl.setLoading('Receiving data...', formPanl.getForm());
							var confirmFields = '';
							var rejectBtn = Ext.getCmp('confirmRepoRejectBtn');
							var confirmBtn = Ext.getCmp('confirmRepoConfirmBtn');

							formPanl.getForm().reset();

							Ext.Ajax.request({
								url : 'getRepo.action',
								params : {
									id : findId,
								},
								success : function(response) {
									var obj = Ext.decode(response.responseText);

									Ext.ComponentQuery.query('#confirmRepoDealCode')[0].setText('Deal Code :' + obj.data.dealCode);
									Ext.ComponentQuery.query('#confirmRepoDealStatus')[0].setText('Deal Status :' + obj.data.status);

									var valDtLocal = Ext.ComponentQuery.query('#confirmRepoValueDt')[0];
									valDtLocal.format = 'd/m/Y';
									valDtLocal.setValue(obj.data.valueDate);

									var matDtLocal = Ext.ComponentQuery.query('#confirmRepoMaturityDt')[0];
									matDtLocal.format = 'd/m/Y';
									matDtLocal.setValue(obj.data.valueDate);

									var lblMaturityDate = Ext.ComponentQuery.query('#confirmRepoDuration')[0];
									var durationDays = (matDtLocal.getValue() - valDtLocal.getValue()) / 86400000;
									lblMaturityDate.setText('Duration: '.concat(durationDays.toString().concat(' days.')));

									formPanl.getForm().load({
										url : 'getRepo.action',
										params : {
											id : findId,
										},
										success : function(response) {

											if (rec.get('status') === 'Initial') {

												Ext.Ajax.request({
													url : 'confFields.action',
													params : {
														screen : 'RecordRepo',
													},
													success : function(response) {
														var objFive = Ext.decode(response.responseText);
														confirmFields = objFive.values;
														// formPanl.setLoading('Receiving
														// data...',
														// formPanl.getForm());

														formPanl.getForm().getFields().each(function(field) {
															field.setDisabled(true);
														});

														var confFieldsArrray = confirmFields.split(";");
														var i;
														var confFieldLocal;
														var confFieldQuery;
														for (i = 0; i < confFieldsArrray.length - 1; i++) {
															confFieldQuery = '#' + confFieldsArrray[i];
															confFieldLocal = Ext.ComponentQuery.query(confFieldQuery)[0];
															confFieldLocal.enable();
															confFieldLocal.reset();
														}
														Ext.ComponentQuery.query('#confirmRepoResWindow')[0].close();
														Ext.ComponentQuery.query('#confirmRepoTrigField')[0].enable();
														if (obj.data.withholdingTax == 0) {
															Ext.ComponentQuery.query('#confirmRepoWithholdRate')[0].disable();
															Ext.ComponentQuery.query('#confirmRepoWithholdRate')[0].reset();
														}
														formPanl.setLoading(false);
													},
													failure : function(form, action) {
														Ext.ComponentQuery.query('#confirmRepoResWindow')[0].close();
														Ext.Msg.alert('Error!', 'Failed to load Confirmation Fields!');
														formPanl.setLoading(false);
													}
												});
											} else {
												Ext.ComponentQuery.query('#confirmRepoFundCmb')[0].disable();
												Ext.ComponentQuery.query('#confirmRepoResWindow')[0].close();
												Ext.ComponentQuery.query('#confirmRepoTrigField')[0].enable();
												formPanl.setLoading(false);
											}
											// ConfirmRepo.setMatVal();

										},
										failure : function(form, action) {
											formPanl.setLoading(false);
											Ext.Msg.alert("An Error occured. Load failed");
										}
									});

								},
								failure : function(form, action) {
									formPanl.setLoading(false);
								}
							});

							if ('status' === 'Confirmed') { // If only viewing
								// permissions
								formPanl.getForm().getFields().each(function(field) {
									field.setDisabled(true);
								});
								rejectBtn.disable();
								confirmBtn.disable();
							} else {
								if (rec.get('status') === 'Initial') {
									rejectBtn.enable();
									confirmBtn.enable();
								} else {
									rejectBtn.disable();
									confirmBtn.disable();
								}
							}
							// this.up('.window').close();
							Ext.ComponentQuery.query('#confirmRepoTrigField')[0].enable();
							// formPanl.setLoading(false);
						}
					}
				});

				Ext.create('Ext.window.Window', {
					title : 'Sales',
					id : 'confirmRepoResWindow',
					height : 330,
					frame : true,
					width : 500,
					constrain : true,
					resizable : false,
					layout : {
						type : 'fit'
					},
					items : [ resultWindow ]
				}).show();

			}
		} ]
	});
};

ConfirmRepo.getFieldSet1 = function() {

	Ext.create('Ext.data.Store', {
		fields : [ {
			name : 'id',
			type : 'int',
		}, {
			name : 'fundName',
			type : 'string',
		}, {
			name : 'fundCode',
			type : 'string',
		} ],
		storeId : 'confirmRepoFundStore',
	});

	Ext.Ajax.request({
		url : 'getFundsForDeal.action',
		params : {
			querry : 'REPO',
		},
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			Ext.data.StoreManager.lookup('confirmRepoFundStore').loadRawData(obj.fundList);
		},
		failure : function(response) {
			Ext.Msg.alert('Error!', 'Failed to load Fund List : ' + response);
		},
	});

	Ext.create('Ext.data.Store', {
		fields : [ {
			name : 'id',
			type : 'int',
		}, {
			name : 'name',
			type : 'string',
		}, {
			name : 'code',
			type : 'string',
		} ],
		storeId : 'confirmRepoIssuerStore',
	});

	Ext.Ajax.request({
		url : 'getIssuers.action',
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			Ext.data.StoreManager.lookup('confirmRepoIssuerStore').loadRawData(obj.issuerList);
		},
		failure : function(response) {
			Ext.Msg.alert('Error!', 'Failed to Load Issuers!');
		}

	});

	var selectFundComboBox = Ext.create('Ext.form.ComboBox', {
		name : 'fund',
		fieldLabel : 'Fund',
		store : Ext.data.StoreManager.lookup('confirmRepoFundStore'),
		valueField : 'id',
		queryMode : 'local',
		flex : 1,
		id : 'confirmRepoFundCmb',
		padding : '0 10 0 0',
		labelWidth : 120,
		autoScroll : true,
		allowBlank : false,
		msgTarget : 'under',
		tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{fundName} - <b>{fundCode}</b><br/></div>', '</tpl>'),
		displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{fundName}', '</tpl>'),
	});

	var selectIssuerComboBox = Ext.create('Ext.form.ComboBox', {
		name : 'issuer',
		fieldLabel : 'Issuer',
		store : Ext.data.StoreManager.lookup('confirmRepoIssuerStore'),
		valueField : 'id',
		queryMode : 'local',
		autoScroll : true,
		flex : 1,
		padding : '0 5 0 0',
		// style:'margin-top:10px;',
		id : 'confirmRepoIssuer',
		allowBlank : false,
		blankText : 'Please select an Issuer to proceed',
		msgTarget : 'under',
		editable : false,
		tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{name} - <b>{code}</b><br/></div>', '</tpl>'),
		displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{name}', '</tpl>'),
	});

	return Ext.create('Ext.form.FieldSet', {
		title : 'Basic',
		defaults : {
			labelWidth : 175,
			anchor : '100%'
		},
		items : [ {
			xtype : 'label',
			id : 'confirmRepoDealCode',
			style : 'font-weight:600;margin-top:7px;',
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ selectFundComboBox, selectIssuerComboBox ]
		}, {
			xtype : 'label',
			id : 'confirmRepoDealStatus',
			style : 'font-weight:600;margin-top:7px;',
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'datefield',
				fieldLabel : 'Value Date',
				name : 'valueDate',
				allowBlank : false,
				id : 'confirmRepoValueDt',
				blankText : 'Please enter a Start Date',
				msgTarget : 'under',
				flex : 1,
				id : 'confirmRepoValueDt',
				padding : '0 10 0 0',
				labelWidth : 120,
				format : 'd/m/Y',
				emptyText : 'dd/mm/yyyy',
				minValue : new Date(),
				listeners : {
					'change' : {
						fn : function(field, newVal, oldVal) {
							var dfMaturityDate = Ext.ComponentQuery.query('#confirmRepoMaturityDt')[0];
							if (dfMaturityDate.getValue() != null) {
								var lblMaturityDate = Ext.ComponentQuery.query('#confirmRepoDuration')[0];
								if (this.getValue() > dfMaturityDate.getValue()) {
									Ext.MessageBox.alert('Error', 'Value Date cannot be greater than Maturity Date.');
									this.setValue(null);
									lblMaturityDate.setText('');
								} else {
									var durationDays = (dfMaturityDate.getValue() - this.getValue()) / 86400000;
									// alert(durationDays.toString());
									lblMaturityDate.setText('Duration: '.concat(durationDays.toString().concat(' days.')));
									ConfirmRepo.setMatVal();
								}

							}

						}
					}
				}
			}, {
				xtype : 'datefield',
				fieldLabel : 'Maturity Date',
				name : 'maturityDate',
				id : 'confirmRepoMaturityDt',
				allowBlank : false,
				blankText : 'Please enter a Maturity Date',
				msgTarget : 'under',
				flex : 1,
				padding : '0 5 0 0',
				// style:'margin-top:10px;',
				format : 'd/m/Y',
				emptyText : 'dd/mm/yyyy',
				minValue : new Date(),
				listeners : {
					'change' : {
						fn : function(field, newVal, oldVal) {
							// var btnColAdd =
							// Ext.ComponentQuery.query('#confirmRepoAddColBtn')[0];
							var dfValueDate = Ext.ComponentQuery.query('#confirmRepoValueDt')[0];
							if (dfValueDate.getValue() != null) {
								var lblValueDate = Ext.ComponentQuery.query('#confirmRepoDuration')[0];
								if (dfValueDate.getValue() > this.getValue()) {
									Ext.MessageBox.alert('Error', 'Maturity Date cannot be smaller than Value Date.');
									this.setValue(null);
									lblValueDate.setText('');
								} else {
									// btnColAdd.enable();
									var durationDays = (this.getValue() - dfValueDate.getValue()) / 86400000;
									// alert(durationDays.toString());
									lblValueDate.setText('Duration: '.concat(durationDays.toString().concat(' days.')));
									ConfirmRepo.setMatVal();
								}

							}

						}
					}
				}
			} ]
		}, {
			xtype : 'label',
			id : 'confirmRepoDuration',
			style : 'margin:5px;',

		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'combo',
				fieldLabel : 'Delevary Method',
				store : CommenStore.delevaryMethodStore,
				valueField : 'id',
				flex : 1,
				labelWidth : 120,
				name : 'delevarymethode',
				id : 'confirmRepoDelevaryMethod',
				padding : '0 10 0 0',
				displayField : 'code',
				tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{code} - <b>{description}</b><br/></div>', '</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{code} - {description}', '</tpl>'),
				listeners : {
					change : function(combo, record, index) {
						if (combo.getValue() == "" || combo.getValue() == "&nbsp;" || combo.getValue == 0) {
							combo.setValue(null);
						}
					}
				}
			}, {
				xtype : 'combo',
				fieldLabel : 'Dealer',
				store : CommenStore.dealersStore,
				valueField : 'id',
				flex : 1,
				padding : '0 5 0 0',
				name : 'dealerCode',
				id : 'confirmRepoDealer',
				displayField : 'code',
				tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{code} - <b>{name}</b><br/></div>', '</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{code} - {name}', '</tpl>'),
				listeners : {
					change : function(combo, record, index) {
						if (combo.getValue() == "" || combo.getValue() == "&nbsp;" || combo.getValue == 0) {
							combo.setValue(null);
						}
					}
				}
			} ]
		}, {
			xtype : 'combo',
			labelWidth : 120,
			fieldLabel : 'Settlement Method',
			store : CommenStore.settlmentStore,
			valueField : 'id',
			anchor : '50%',
			name : 'settlementCode',
			id : 'confirmRepoSettlementMethod',
			padding : '0 10 0 0',
			displayField : 'code',
			tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{code} - <b>{description}</b><br/></div>', '</tpl>'),
			displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{code} - {description}', '</tpl>'),
			listeners : {
				change : function(combo, record, index) {
					if (combo.getValue() == "" || combo.getValue() == "&nbsp;" || combo.getValue == 0) {
						combo.setValue(null);
					}
				}
			}
		} ]
	});

};

ConfirmRepo.getFieldSet2 = function() {

	return Ext.create('Ext.form.FieldSet', {
		title : 'Parameters',
		defaults : {
			labelWidth : 175
		},
		items : [ {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'textfield',
				minValue : 0,
				name : 'principleValue',
				padding : '0 10 0 0',
				allowBlank : false,
				// style:'margin-top:10px;',
				id : 'confirmRepoPrincipleVal',
				fieldLabel : 'Principle Value',
				flex : 1,
				fieldStyle : "text-align:right;",
				maskRe : /[\d\,.]/,
				listeners : {
					blur : function() {
						this.setRawValue(Ext.util.Format.number(this.value, '0,000.0000'));
						console.log(Ext.util.Format.number(this.value, '0,000.00'));
						ConfirmRepo.setMatVal();
					},
					render : function() {
						this.setRawValue(Ext.util.Format.number(this.value, '0,000.0000'));
					}
				}
			}, {
				xtype : 'textfield',
				vtype : 'Rate',
				validateOnBlur : true,
				maskRe : /[\d\%.]/,
				allowBlank : false,
				name : 'actualRate',
				flex : 1,
				padding : '0 5 0 0',
				fieldLabel : 'Actual Rate',
				id : 'confirmRepoActRate',
				listeners : {
					blur : function() {
						var value = Ext.util.Format.number(this.value.replace(/%/g, ''), '000.00');
						this.setRawValue(value + "%");
						ConfirmRepo.setMatVal();
					},
				}
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ new Ext.form.ComboBox({
				store : new Ext.data.Store({
					fields : [ 'dayBasis' ],
					data : [ {
						"dayBasis" : "Act / Act"
					}, {
						"dayBasis" : "Act / 360"
					}, {
						"dayBasis" : "Act / 364"
					}, {
						"dayBasis" : "Act / 365"
					}, {
						"dayBasis" : "30 / 360"
					}, {
						"dayBasis" : "30 / 365"
					} ]
				}),
				displayField : 'dayBasis',
				valueField : 'dayBasis',
				mode : 'local',
				flex : 4,
				padding : '0 10 0 0',
				// style:'margin-top:10px;',
				value : 'Act / 365',
				fieldLabel : 'Day Basis',
				forceSelection : true,
				name : 'dayBasis',
				id : 'confirmRepoDayBasis',
				listeners : {
					select : {
						fn : function(combo, value) {
							ConfirmRepo.setMatVal();
						}
					}
				},
			}), {
				xtype : 'label',
				flex : 2,
				// style : 'font-weight:600;',
				style : 'margin-top:6px;',
				text : 'Maturity Value:',
			}, {
				xtype : 'label',
				flex : 2,
				id : 'confirmRepoDealMatValLbl',
				style : 'font-weight:600;margin-top:6px;',
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'checkboxfield',
				boxLabel : 'Withholding Tax',
				id : 'confirmRepoWithholdingCB',
				name : 'withholdingTax',
				flex : 1,
				padding : '0 5 0 0',
				inputValue : '1',
				listeners : {
					change : function(field, newVal) {
						if (newVal) {
							var wrt = Ext.ComponentQuery.query('#confirmRepoWithholdRate')[0];
							wrt.enable();
						} else {
							var wrt = Ext.ComponentQuery.query('#confirmRepoWithholdRate')[0];
							wrt.disable();
						}
					}
				}
			}, {
				xtype : 'textfield',
				vtype : 'Rate',
				validateOnBlur : true,
				maskRe : /[\d\%.]/,
				id : 'confirmRepoWithholdRate',
				allowBlank : false,
				name : 'withholdingTaxRate',
				fieldLabel : 'Withholding Tax Rate',
				flex : 1,
				padding : '0 5 0 5',
				disabled : true,
				listeners : {
					blur : function() {
						var value = Ext.util.Format.number(this.value.replace(/%/g, ''), '000.00');
						this.setRawValue(value + "%");
						ConfirmRepo.setMatVal();
					}
				},
			} ]
		} ]
	});
};

ConfirmRepo.getFieldSet3 = function() {
	var collateralStore = new Ext.data.Store({
		model : 'Collateral',
		storeId : 'collateralStore'
	});
	var instruments = Ext.create('Ext.data.Store', {
		fields : [ {
			name : 'name',
			type : 'string'
		}, {
			name : 'number',
			type : 'string'
		}, {
			name : 'maturityDate',
			type : 'date',
			dateFormat : 'd/m/Y'
		} ],
		data : [ {
			"name" : "CP Test",
			'number' : '123456',
			'maturityDate' : '29/06/2014'
		}, {
			"name" : "Test Debenture",
			'number' : '123458',
			'maturityDate' : '29/07/2014'
		}, {
			"name" : "TBILL",
			'number' : '23456',
			'maturityDate' : '31/08/2014'
		}, {
			"name" : "Tbond",
			'number' : '34-45',
			'maturityDate' : '25/09/2014'
		}, {
			"name" : "Instrument",
			'number' : '890678',
			'maturityDate' : '29/08/2019'
		} ]
	});

	var selectInsTypeComboBox = Ext.create('Ext.form.ComboBox', {
		name : 'instrumentType',
		id : 'confirmRepoInstrumentType',
		fieldLabel : 'Instrument Type',
		store : instrumentTypes,
		valueField : 'type',
		autoScroll : true,
		flex : 1,
		padding : '0 10 0 0',
		// style:'margin-top:10px;',
		allowBlank : false,
		blankText : 'Please select an Instrument Type to proceed',
		msgTarget : 'under',
		editable : false,
		tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{type}</div>', '</tpl>'),
		displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{type}', '</tpl>'),
		listeners : {
			select : {
				fn : function(combo, value) {
					var comboInsCode = Ext.ComponentQuery.query('#confirmRepoInsNo')[0];
					instrumentStore.clearFilter(true);
					instrumentStore.filter('type', instrumentTypes.getAt(instrumentTypes.find('type', combo.getValue())).get('type'));
					comboInsCode.bindStore(instrumentStore);
					comboInsCode.clearValue();
					comboInsCode.show();

					/*
					 * var issuerCmb =
					 * Ext.ComponentQuery.query('#confirmRepoIssuerCmb')[0]; if
					 * (instrumentTypes.getAt(instrumentTypes.find('type',
					 * combo.getValue())).get('issuer') == 'government') {
					 * issuerCmb.clearValue(); issuerCmb.disable();
					 * 
					 * }else{ issuerCmb.enable(); }
					 */
				}
			}
		}
	});

	var finalFieldSet = Ext.create('Ext.form.FieldSet', {
		title : 'Collateral Information',
		defaults : {
			labelWidth : 175,
			anchor : '100%'
		},
		items : [ {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ selectInsTypeComboBox, Ext.create('Ext.form.ComboBox', {
				fieldLabel : 'Instrument No',
				store : instrumentStore,
				valueField : 'code',
				displayField : 'name',
				id : 'confirmRepoInsNo',
				autoScroll : true,
				queryMode : 'local',
				allowBlank : false,
				blankText : 'Please select an Instrument to proceed',
				msgTarget : 'under',
				editable : false,
				flex : 1,
				padding : '0 5 0 0',
				// style:'margin-top:10px;',
				tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{name}</div>', '</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{name}', '</tpl>'),
				listeners : {
					select : {
						fn : function(combo, value) {
							var repInsCmb = Ext.ComponentQuery.query('#confirmRepoInstrumentType')[0];
							var repPrimaryDealer = Ext.ComponentQuery.query('#confirmRepoPrimDealer')[0];
							var repIssuerCB = Ext.ComponentQuery.query('#confirmRepoIssuerCmb')[0];
							if (instrumentTypes.getAt(instrumentTypes.find('type', repInsCmb.getValue())).get('issuer') === 'government') {
								repPrimaryDealer.setValue(instrumentStore.getAt(instrumentStore.find('code', combo.getValue())).get('issuer'));
								repIssuerCB.clearValue();
							} else {
								repIssuerCB.setValue(instrumentStore.getAt(instrumentStore.find('code', combo.getValue())).get('issuer'));
								repPrimaryDealer.clearValue();
							}

							var dfColMaturityDate = Ext.ComponentQuery.query('#confirmRepoColMatDt')[0];
							dfColMaturityDate.setValue(instrumentStore.getAt(instrumentStore.find('code', combo.getValue())).get('maturityDate'));
							// dfColMaturityDate.disable();

						}
					}
				}
			}) ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ Ext.create('Ext.form.ComboBox', {
				name : 'issuer',
				fieldLabel : 'Issuer',
				id : 'confirmRepoIssuerCmb',
				store : issuers,
				valueField : 'name',
				autoScroll : true,
				allowBlank : false,
				disabled : true,
				flex : 1,
				padding : '0 10 0 0',
				// style:'margin-top:10px;',
				blankText : 'Please select an Issuer to proceed',
				msgTarget : 'under',
				editable : false,
				tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{name}</div>', '</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{name}', '</tpl>')
			}), Ext.create('Ext.form.ComboBox', {
				fieldLabel : 'Primary Dealer',
				store : primaryDealerStore,
				valueField : 'name',
				id : 'confirmRepoPrimDealer',
				autoScroll : true,
				// editable : false,
				disabled : true,
				flex : 1,
				padding : '0 5px 0 0',
				// style:'margin-top:10px;',
				tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{name}</div>', '</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{name}', '</tpl>')
			}) ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'datefield',
				fieldLabel : 'Maturity Date',
				id : 'confirmRepoColMatDt',
				allowBlank : false,
				flex : 1,
				padding : '0 10 0 0',
				// style:'margin-top:10px;',
				format : 'd/m/Y',
				emptyText : 'dd/mm/yyyy',
				disabled : true,
				minValue : new Date(),
			}, {
				xtype : 'numberfield',
				minValue : 0,
				name : 'insValue',
				id : 'confirmRepoInsValue',
				fieldLabel : 'Face Value',
				flex : 1,
				allowBlank : false,
				padding : '0 5px 0 0',
				// style:'margin-top:10px;',
				blankText : 'Please enter the Value',
				msgTarget : 'under'
			} ]
		}, {
			xtype : 'fieldset',
			layout : 'fit',
			items : [ Ext.create('Ext.grid.Panel', {
				id : 'confirmRepoCollateralPanel',
				store : Ext.data.StoreManager.lookup('collateralStore'),
				columns : [ {
					text : 'Instrument Type',
					dataIndex : 'instrumentType'
				}, {
					text : 'Instrument No',
					dataIndex : 'instrumentNo',
					flex : 1
				}, {
					text : 'Issuer/PrDealer',
					dataIndex : 'issuer',
					flex : 1
				}, {
					xtype : 'datecolumn',
					format : 'd-m-Y',
					text : 'Maturity',
					dataIndex : 'maturityDate',
					flex : 1
				}, {
					text : 'Value',
					dataIndex : 'value'
				} ],
				height : 250,
				width : 450,
				dockedItems : [ {
					xtype : 'pagingtoolbar',
					id : 'confirmRepoColGridToolBar',
					store : Ext.data.StoreManager.lookup('collateralStore'),
					dock : 'bottom',
					displayInfo : true
				} ],
				tbar : [ '->', {
					text : 'Add',
					id : 'confirmRepoAddColBtn',
					disabled : true,
					handler : function() {
						var repMatDate = Ext.ComponentQuery.query('#confirmRepoMaturityDt')[0];
						var repColMatDate = Ext.ComponentQuery.query('#confirmRepoColMatDt')[0];
						var cbInsType = Ext.ComponentQuery.query('#confirmRepoInstrumentType')[0];
						var tfInsNo = Ext.ComponentQuery.query('#confirmRepoInsNo')[0];
						var tfInsVal = Ext.ComponentQuery.query('#confirmRepoInsValue')[0];
						var repPrimaryDealer = Ext.ComponentQuery.query('#confirmRepoPrimDealer')[0];
						var repIssuer = Ext.ComponentQuery.query('#confirmRepoIssuerCmb')[0];

						if (cbInsType.getValue() === null) {
							Ext.MessageBox.alert('Error', 'Please select an Instrument type.');
						} else if (tfInsNo.getValue() === '' || tfInsNo.getValue() === null) {
							Ext.MessageBox.alert('Error', 'Please enter the Instrument Number.');
						} else if (tfInsVal.getValue() === 0) {
							Ext.MessageBox.alert('Error', 'Please check the Instrument Value.');
						} else if (repPrimaryDealer.getValue() === null && (repIssuer.getValue() === '' || repIssuer.getValue() === null)) {
							Ext.MessageBox.alert('Error', 'Issuer/Primary Dealer is requered.');
						} else {
							// console.log((repPrimaryDealer.getValue()===null)
							// ? repIssuer.getValue() :
							// repPrimaryDealer.getValue());
							if (repColMatDate.getValue() < repMatDate.getValue()) {
								Ext.Msg.confirm('Confirm Box', 'Collateral Matures too early! Do you wish to continue?', function(buttonText) {
									if (buttonText == "yes") {
										var recordIndex = collateralStore.findBy(function(record, id) {
											if (record.get('instrumentType') === cbInsType.getValue() && record.get('instrumentNo') === tfInsNo.getValue()) {
												return true;
											}
											return false;
										});
										if (recordIndex != -1) {
											Ext.MessageBox.alert('Error!', 'Duplicate Entry!!!');
										} else {
											var userco = Ext.ModelManager.create({
												instrumentType : cbInsType.getValue(),
												instrumentNo : tfInsNo.getValue(),
												issuer : (repPrimaryDealer.getValue() === null) ? repIssuer.getValue() : repPrimaryDealer.getValue(),
												maturityDate : repColMatDate.getValue(),
												value : tfInsVal.getValue()
											}, 'Collateral');
											collateralStore.add(userco);
											var pagingToolbar = Ext.ComponentQuery.query('#confirmRepoColGridToolBar')[0];
											collateralStore.totalCount = collateralStore.count();
											pagingToolbar.onLoad();
										}
									}
								});
							} else {
								var recordIndex = collateralStore.findBy(function(record, id) {
									if (record.get('instrumentType') === cbInsType.getValue() && record.get('instrumentNo') === tfInsNo.getValue()) {
										return true;
									}
									return false;
								});
								if (recordIndex != -1) {
									Ext.MessageBox.alert('Error!', 'Duplicate Entry!!!');
								} else {
									var userco = Ext.ModelManager.create({
										instrumentType : cbInsType.getValue(),
										instrumentNo : tfInsNo.getValue(),
										issuer : (repPrimaryDealer.getValue() === null) ? repIssuer.getValue() : repPrimaryDealer.getValue(),
										maturityDate : repColMatDate.getValue(),
										value : tfInsVal.getValue()
									}, 'Collateral');
									collateralStore.add(userco);
									var pagingToolbar = Ext.ComponentQuery.query('#confirmRepoColGridToolBar')[0];
									collateralStore.totalCount = collateralStore.count();
									pagingToolbar.onLoad();
								}
							}
						}
					}
				}, {
					text : 'Remove',
					handler : function() {

						var collateralsStore = Ext.data.StoreManager.lookup('collateralStore');
						var pCpnDtStorePanel = Ext.ComponentQuery.query('#confirmRepoCollateralPanel')[0];

						var sm = pCpnDtStorePanel.getSelectionModel();
						var sel = sm.getSelection();
						pCpnDtStorePanel.store.remove(sel[0]);

						var pagingToolbar = Ext.ComponentQuery.query('#confirmRepoColGridToolBar')[0];
						collateralsStore.totalCount = collateralsStore.count();
						pagingToolbar.onLoad();
					}
				} ]

			}) ]
		} ]
	});
	return finalFieldSet;
};

ConfirmRepo.getCenterPanel = function() {
	var searchBar = ConfirmRepo.getSearchBar();
	var filedset1 = ConfirmRepo.getFieldSet1();
	var filedset2 = ConfirmRepo.getFieldSet2();
	// var filedset3 = ConfirmRepo.getFieldSet3();

	CommenStore.settlmentStore.load();
	CommenStore.dealersStore.load();
	CommenStore.delevaryMethodStore.load();

	var formPanel = Ext.create('Ext.form.FormPanel', {
		bodyPadding : '20',
		id : 'confirmRepoFormPanel',
		autoScroll : true,
		frame : true,
		defaults : {
			labelWidth : 175,
			anchor : '72%',
		},
		fieldDefaults : {
			labelAlign : 'left',
			labelWidth : 150,
		},
		title : 'Record REPO',
		items : [ searchBar, filedset1, filedset2, /* filedset3 */],
		buttonAlign : 'center',
		buttons : [ {
			text : 'Cancel',
			handler : function() {
				App.Core.removeScreen();
			}
		}, {
			text : 'Reset',
			handler : function() {
				this.up('form').getForm().reset();
				Ext.ComponentQuery.query('#confirmRepoDuration')[0].setText('');
				Ext.ComponentQuery.query('#confirmRepoDealCode')[0].setText('');
				Ext.ComponentQuery.query('#confirmRepoDealStatus')[0].setText('');
				Ext.ComponentQuery.query('#confirmRepoDealMatValLbl')[0].setText('');
				Ext.ComponentQuery.query('#confirmRepoFundCmb')[0].enable();
				Ext.ComponentQuery.query('#confirmRepoIssuer')[0].enable();
				Ext.ComponentQuery.query('#confirmRepoValueDt')[0].enable();
				Ext.ComponentQuery.query('#confirmRepoMaturityDt')[0].enable();
				Ext.ComponentQuery.query('#confirmRepoPrincipleVal')[0].enable();
				Ext.ComponentQuery.query('#confirmRepoActRate')[0].enable();
				Ext.ComponentQuery.query('#confirmRepoDayBasis')[0].enable();
				Ext.ComponentQuery.query('#confirmRepoWithholdingCB')[0].enable();
			}
		}, {
			text : 'Reject',
			id : 'confirmRepoRejectBtn',
			itemId : 'rejectButton',
			handler : function() {
				var form = this.up('form').getForm();

				form.url = 'rejectRepo.action';
				formPanel.setLoading('Rejecting...');
				formPanel.getForm().getFields().each(function(field) {
					field.setDisabled(true);
				});
				Ext.ComponentQuery.query('#confirmRepoTrigField')[0].enable();

				/*
				 * var valueDtField =
				 * Ext.ComponentQuery.query('#confirmRepoValueDt')[0]; var
				 * maturityDtField =
				 * Ext.ComponentQuery.query('#confirmRepoMaturityDt')[0];
				 */
				if (Ext.ComponentQuery.query('#confirmRepoDealCode')[0].text == null) {
					formPanel.setLoading(false);
					Ext.Msg.alert('Error', 'Please select a Deal');
				} else if (Ext.ComponentQuery.query('#confirmRepoDealCode')[0].text.length <= 11) {
					formPanel.setLoading(false);
					Ext.Msg.alert('Error', 'Invalid Deal');
				} else {
					var dealCode = Ext.ComponentQuery.query('#confirmRepoDealCode')[0].text.substr(11);
					form.submit({
						params : {
							'user' : 'createdUser',
							'dealCode' : dealCode,
						// 'valueDate' :
						// Ext.util.Format.date(valueDtField.getValue()),
						// 'maturityDate' :
						// Ext.util.Format.date(maturityDtField.getValue()),
						// 'maturityValue' : 2500.0000,
						},
						success : function(form, action) {
							form.reset();
							Ext.Msg.alert('Success', 'Repo Rejected.<br> Deal Code <b>' + action.result.dealCode + '</b>');
							Ext.ComponentQuery.query('#confirmRepoDuration')[0].setText('');
							Ext.ComponentQuery.query('#confirmRepoDealCode')[0].setText('');
							Ext.ComponentQuery.query('#confirmRepoDealStatus')[0].setText('');
							Ext.ComponentQuery.query('#confirmRepoDealMatValLbl')[0].setText('');
							formPanel.setLoading(false);
						},
						failure : function(form, action) {
							Ext.Msg.alert('Failed', 'There is some error returned from the server.<br>' + action.result.status);
							formPanel.setLoading(false);
						}
					});
				}
			}

		}, {

			text : 'Confirm',
			id : 'confirmRepoConfirmBtn',
			itemId : 'confirmButton',
			handler : function() {
				var form = this.up('form').getForm();
				form.url = 'confRepo.action';

				Ext.ComponentQuery.query('#confirmRepoFundCmb')[0].enable();
				Ext.ComponentQuery.query('#confirmRepoIssuer')[0].enable();
				Ext.ComponentQuery.query('#confirmRepoValueDt')[0].enable();
				Ext.ComponentQuery.query('#confirmRepoMaturityDt')[0].enable();
				Ext.ComponentQuery.query('#confirmRepoPrincipleVal')[0].enable();
				Ext.ComponentQuery.query('#confirmRepoActRate')[0].enable();
				Ext.ComponentQuery.query('#confirmRepoDayBasis')[0].enable();
				Ext.ComponentQuery.query('#confirmRepoWithholdingCB')[0].enable();
				if (Ext.ComponentQuery.query('#confirmRepoWithholdingCB')[0].getValue === 1) {
					Ext.ComponentQuery.query('#confirmRepoWithholdRate')[0].enable();
				}

				if (form.isValid()) {
					formPanel.setLoading('Confirming...');

					var valueDtField = Ext.ComponentQuery.query('#confirmRepoValueDt')[0];
					var maturityDtField = Ext.ComponentQuery.query('#confirmRepoMaturityDt')[0];
					var dealCode = Ext.ComponentQuery.query('#confirmRepoDealCode')[0].text.substr(11);

					form.submit({
						params : {
							'valueDate' : Ext.util.Format.date(valueDtField.getValue()),
							'maturityDate' : Ext.util.Format.date(maturityDtField.getValue()),
							'user' : 'confirmedUser',
							'dealCode' : dealCode,
						},
						success : function(form, action) {
							form.reset();
							Ext.Msg.alert('Success', 'Repo confirmed.<br> Deal Code <b>' + action.result.dealCode + '</b>');
							formPanel.setLoading(false);
							Ext.ComponentQuery.query('#confirmRepoDuration')[0].setText('');
							Ext.ComponentQuery.query('#confirmRepoDealCode')[0].setText('');
							Ext.ComponentQuery.query('#confirmRepoDealStatus')[0].setText('');
							Ext.ComponentQuery.query('#confirmRepoDealMatValLbl')[0].setText('');
						},
						failure : function(form, action) {
							Ext.Msg.alert('Failed', 'There is some error returned from the server.<br><b>' + action.result.status + '</b>');
							formPanel.setLoading(false);
						}
					});
				} else {
					Ext.Msg.alert("ERROR!", "Form Incomplete. Please check!");
				}
			}
		} ]
	});
	return formPanel;
};

ConfirmRepo.getRollOverDeal = function(fund, issuer, valueDate, principaleValue) {

	var panel = ConfirmRepo.getCenterPanel();
	var tttfundStore = Ext.data.StoreManager.lookup('confirmRepoFundStore');
	var tttissuersStore = Ext.data.StoreManager.lookup('confirmRepoIssuerStore');
	tttfundStore.removeAll();
	tttissuersStore.removeAll();

	Ext.Ajax.request({
		url : 'getFundsForDeal.action',
		params : {
			querry : 'REPO',
		},
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			tttfundStore.loadRawData(obj.fundList);
			Ext.getCmp('confirmRepoFundCmb').setValue(tttfundStore.getAt(tttfundStore.find('fundCode', fund)).get('id'));
		},
		failure : function(response) {
			Ext.Msg.alert('Error!', 'Failed to load Fund List : ' + response);
		},
	});

	Ext.Ajax.request({
		url : 'getIssuers.action',
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			tttissuersStore.loadRawData(obj.issuerList);
			Ext.getCmp('confirmRepoIssuer').setValue(tttissuersStore.getAt(tttissuersStore.find('code', issuer)).get('id'));
		},
		failure : function(response) {
			Ext.Msg.alert('Error!', 'Failed to Load Issuers!');
		}

	});

	Ext.getCmp('confirmRepoIssuer').setValue(issuer);
	Ext.getCmp('confirmRepoValueDt').setValue(valueDate);
	Ext.getCmp('confirmRepoPrincipleVal').setValue(principaleValue);
	return panel;
};

ConfirmRepo.setMatValPrev = function() {
	// alert('Satrt');
	var valueDt = Ext.ComponentQuery.query('#confirmRepoValueDt')[0].getValue();
	// console.log('1:'+valueDt);
	if (valueDt == null)
		return;
	var maturityDt = Ext.ComponentQuery.query('#confirmRepoMaturityDt')[0].getValue();
	// console.log('2:'+maturityDt);
	if (maturityDt == null)
		return;
	var prValStr = Ext.ComponentQuery.query('#confirmRepoPrincipleVal')[0].getValue();
	// console.log('3:'+prValStr);
	if (prValStr == null || prValStr === '')
		return;
	var ActRate = Ext.ComponentQuery.query('#confirmRepoActRate')[0].getValue();
	// console.log('4:'+ActRate);
	if (ActRate == null)
		return;
	var dayBasis = Ext.ComponentQuery.query('#confirmRepoDayBasis')[0].getValue();
	// console.log('5:'+dayBasis);
	if (dayBasis == null)
		return;

	var dur = (maturityDt - valueDt) / 86400000;
	var prVal = parseFloat(prValStr.replace(/\,/g, ''));
	// alert((prVal*ActRate*dur)/(100*365));
	var res = ((prVal * ActRate * dur) / (100 * 365)).toFixed(4);
	Ext.ComponentQuery.query('#confirmRepoDealMatValLbl')[0].setText(res);
	return (res);
};

ConfirmRepo.setMatVal = function() {
	var valueDt = Ext.ComponentQuery.query('#confirmRepoValueDt')[0].getValue();
	if (valueDt == null)
		return;

	var maturityDt = Ext.ComponentQuery.query('#confirmRepoMaturityDt')[0].getValue();
	if (maturityDt == null)
		return;

	var principleValue = Ext.ComponentQuery.query('#confirmRepoPrincipleVal')[0].getValue();
	if (principleValue == '' || principleValue == null)
		return;

	var dayBasis = Ext.ComponentQuery.query('#confirmRepoDayBasis')[0].getValue();
	if (dayBasis == null)
		return;

	var actualRate = Ext.ComponentQuery.query('#confirmRepoActRate')[0].getValue();
	if (actualRate == null || actualRate == '')
		return;

	var withholdingTax;
	var withholdingTaxRate;
	if (Ext.ComponentQuery.query('#confirmRepoWithholdingCB')[0].getValue()) {
		withholdingTax = 1;
		withholdingTaxRate = Ext.ComponentQuery.query('#confirmRepoWithholdRate')[0].getValue();
	} else {
		withholdingTax = 0;
		withholdingTaxRate = 0;
	}

	Ext.Ajax.request({
		url : 'evalRepo.action',
		params : {
			'valueDate' : Ext.util.Format.date(valueDt),
			'maturityDate' : Ext.util.Format.date(maturityDt),
			'principleValue' : principleValue,
			'actualRate' : actualRate,
			'dayBasis' : dayBasis,
			'withholdingTax' : withholdingTax,
			'withholdingTaxRate' : withholdingTaxRate,
		},
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			Ext.ComponentQuery.query('#confirmRepoDealMatValLbl')[0].setText(obj.maturityValue);
		},
		failure : function(response) {
			Ext.ComponentQuery.query('#confirmRepoDealMatValLbl')[0].setValue('Error :' + obj.status);
		},
	});
};
